<template>
  <a-modal
    width="1000px"
    :dialogStyle="{ top: '20vh' }"
    :visible="visible"
    cancelText="关闭"
    @cancel="visiblehandleCancel"
  >
    <a-form :form="form" layout="inline" :selfUpdate="true" style="margin-bottom: 20px">
      <a-row :gutter="24" >
        <a-col :md="6" style="height:40px">
          <a-form-item label="科室"> 
            <a-select
              placeholder="选择科室"
              allowClear
              show-search
              option-filter-prop="children"
              :filter-option="filterOption"
              style="width: 195.5px"
              v-decorator="['wxworkGroupName', { rules: [{ required: true, message: '请先选择科室！' }] }]"
            >
              <a-select-option  :value="item.id" v-for="(item) in deptList" :key="item.id"> {{item.name}} 
              </a-select-option>  
            </a-select>
          </a-form-item>
        </a-col>  
      </a-row>
    </a-form>

    <a-table 
      :columns="columns"
      :data-source="tableData"
      :loading="tableLoading"
      :pagination="false"
      :rowKey="(record,index)=>index" 
    > 
    
      <template slot="wxworkName" slot-scope="text,record,index">
        <a-input 
          placeholder="别名" 
          :value="text" 
          style="width: 195.5px"
          @change="(e) =>valChange2(e, record, index, 'wxworkName')"  
          :class="record.wxworkNameBorder ? 'colorBorder' : ''"
          @blur="blurChange('wxworkNameBorder', 'wxworkName')" 
        />
         
      </template>
      <template slot="begin" slot-scope="text,record,index">
        <!-- <a-date-picker 
          allow-clear 
          placeholder="开始" 
          :show-time="{ format: 'HH:mm',hideDisabledOptions:true }"
          format="HH:mm"
          mode="time" 
          :value="text"  
          :showToday="false"  
          @change="(date,string) =>valChange(date, string, index, 'begin','beginBorder')"  
          :class="record.beginBorder ? 'colorBorder' : ''"
          @ok="blurChange('beginBorder', 'begin')" 
        /> -->

        <a-time-picker  
          allow-clear 
          placeholder="开始" 
          :show-time="{ format: 'HH:mm',hideDisabledOptions:true }"
          format="HH:mm" 
          :value="text"   
          @change="(date,string) =>valChange(date, string, index, 'begin','beginBorder')"  
          :class="record.beginBorder ? 'colorBorder' : ''" 
        />
      </template>
      <template slot="isday" slot-scope="text,record,index">
        <a-switch :checked="text"  @change="(check) => isdayChange(check, record, index, 'isday')" />
      </template>
      
      <template slot="end" slot-scope="text,record,index">
        <!-- <a-date-picker  
          :disabledTime="() => {
            return disabledDateTime(record)
          }"  
          allow-clear 
          placeholder="结束" 
          :show-time="{ format: 'HH:mm',hideDisabledOptions:true }"
          format="HH:mm"
          mode="time"  
          :value="text" 
          :showToday="false"     
          @change="(date,string) =>valChange(date, string, index, 'end','endBorder')"   
          :class="record.endBorder ? 'colorBorder' : ''"
          @ok="blurChange('endBorder', 'end')" 
        /> -->

        <a-time-picker  
          :disabledHours="() => {
            return disabledHoursFunc(record)
          }"   
          allow-clear 
          :hideDisabledOptions="true"
          placeholder="结束"  
          format="HH:mm" 
          :value="text"    
          @change="(date,string) =>valChange(date, string, index, 'end','endBorder')"   
          :class="record.endBorder ? 'colorBorder' : ''" 
        />
      </template>
    </a-table>
    

    <template slot="footer">
      <a-button @click="visiblehandleCancel()">关闭</a-button>
      <a-button type="primary" @click="submit()"  :loading="submitLoading" >确认</a-button>
    </template>
  </a-modal>
</template>
<script>
import { 
  shiftTypeSelectTgbDepartmentGroup,
  AddTpShiftType,
  shiftTypeSelectTpShiftTypeDept,
  UpdateTpShiftType
} from '@/api/modular/main/rosterList/rosterList'
import moment from 'moment'
import { Calendar } from 'ant-design-vue'
export default {
  props: {
    row_record: {
      type: Object,
      default: () => {
        {
        }
      },
    },
  },
  components: {
    Calendar,
  },
  data() {
    return { 
      visible: false,   
 

      // 日历数据  
      editShow: '',
      submitLoading: false,

      deptList: [],
      form: this.$form.createForm(this),
      shiftList: [
        {
          id: 1,
          name: '早班A1'
        },
        {
          id: 2,
          name: '中班A3'
        },
        {
          id: 3,
          name: '夜班A6'
        }
      ],
      columns: [ 
        { title: '班次', dataIndex: 'name', align:'center' },
        { title: '别名', dataIndex: 'wxworkName', align:'center',  scopedSlots: { customRender: 'wxworkName' } },
        { title: '开始时间', dataIndex: 'begin', align:'center', scopedSlots: { customRender: 'begin' } },
        { title: '次日', dataIndex: 'isday', align:'center', scopedSlots: { customRender: 'isday' } },
        { title: '结束时间', dataIndex: 'end', align:'center', scopedSlots: { customRender: 'end' } }, 
      ],
      tableData: [
        { 
          id: 1,
          name: '早班',
          begin: '',
          end: '',
          status: '1',
          wxworkGroupName: '',
          wxworkName: '早班A1',
          endBorder: false,
          wxworkNameBorder: false,
          isday: false
        },
        { 
          id: 2,
          name: '中班',
          begin: '',
          end: '',
          status: '1',
          wxworkGroupName: '',
          wxworkName: '中班A3',
          endBorder: false,
          wxworkNameBorder: false,
          isday: false
        },
        { 
          id: 3,
          name: '夜班',
          begin: '',
          end: '',
          status: '1',
          wxworkGroupName: '',
          wxworkName: '夜班A6',
          endBorder: false,
          wxworkNameBorder: false,
          isday: false
        },

      ],
      tableLoading: false,
      
    }
  },
  created() {
    // this.createdFunc()  
  },
  methods: {
    disabledHoursFunc(record){
      if(!record.isday){
        let hours = []
        let time = moment(record.begin).format('HH:mm') 
        let timeArr = time.split(':')
        for(let i =0;i<=parseInt(timeArr[0]);i++){
          hours.push(i)
        }
        return hours
      }
      
    },
    showDays(record){ 
      if(record.isday){
        moment(new Date(new Date().getTime()+24*60*60*1000)).format('YYYY-MM-DD')
      }else{
        return moment(new Date()).format('YYYY-MM-DD')
      }
       
    },
    // 是否次日
    isdayChange(check, record, index, t){ 
      this.tableData[index][`${t}`] = check
      this.tableData[index][`end`] = ""
       
      if(check){
        this.tableData[index][`end`] = moment(new Date(new Date().getTime()+24*60*60*1000)).format('YYYY-MM-DD')
      }
      this.tableData = [...this.tableData] 
      console.log(this.tableData)
      
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    valChange2(e, record, index, t) {  
      this.tableData[index][`${t}`] = e.target.value 
      this.tableData = [...this.tableData] 
    },
    // change事件赋值
    valChange(date, stringDate, index, t, rep) { 
      this.tableData[index][`${t}`] = date 
      
      this.blurChange(rep, t)
      if(t == 'begin'){
        this.tableData[index][`end`] = ""
        if(this.tableData[index].isday){
          this.tableData[index][`end`] = moment(new Date(new Date().getTime()+24*60*60*1000)).format('YYYY-MM-DD')
        }
      }
      this.tableData = [...this.tableData]
    },
    blurChange(t, rep) {
       
      // 判读输入框实退金额是否输入
      console.log(t, rep)
      let setData = this.tableData.map((item) => {
        if (item[`${rep}`]) {
          item[`${t}`] = false
        } else {
          item[`${t}`] = true
        }
        return item
      })
      console.log(setData)
      this.tableData = [...setData]
       
    },
    range(start, end) {
      const result = [];
      for (let i = start; i < end; i++) {
        result.push(i);
      }
      return result;
    }, 
    // 禁用
     
    disabledDateTime(record) {    
      return { 
        disabledHours: () => this.range(0, 24).splice(0, Number(moment(record.begin).format('HH'))),
        disabledMinutes: () => this.range(0, Number(moment(record.begin).format('mm'))), 
      };  
    },
    createdFunc() {
      shiftTypeSelectTgbDepartmentGroup().then(res => {
        if(res.code == 200){
          this.deptList = [...res.rows]
        }else{
          this.$message.error(res.msg)
        }
      })
    },
    
    

    

    // 搜索
    filter(inputValue, path) {
      return path.some((option) => option.name.toLowerCase().indexOf(inputValue.toLowerCase()) > -1)
    },

    moment,
    // 禁用
    disabledDate(current) {
      return current && current < moment().startOf('day') //当天之前的不可选，不包括当天
    },

    visiblehandleCancel() {
      this.visible = false  
      this.removeData()
    },
    show(type = '') {
      this.visible = true
      this.editShow = type 
      if(type == 'edit'){
        console.log(this.row_record)
        let sendData = {
          workGroupName: this.row_record.wxworkGroupName
        }
        shiftTypeSelectTpShiftTypeDept(sendData).then(res => {
          if(res.code != 200){
            this.$message.error(res.msg)
          }else{
             
            let newData = res.rows.map(item => {
              return {
                id: item.id,
                name: item.name,
                begin: moment(item.begin, 'HH:mm') ,
                end: moment(item.end, 'HH:mm'),
                status: item.status,
                wxworkGroupName: item.wxworkGroupName,
                wxworkName: item.wxworkName,
                endBorder: false,
                isday: item.isday == 1 ? true : false
              }
            })
            this.tableData = [...newData]
           
            this.form.setFieldsValue({
              "wxworkGroupName": newData[0].wxworkGroupName, 
            })
          }
        })
      } 
      this.createdFunc()
      
      
    },

    removeData(){
      this.tableData = [{ 
        id: 1,
        name: '早班A1',
        begin: '',
        end: '',
        status: '1',
        wxworkGroupName: '',
        wxworkName: '早班A1',
        endBorder: false
      }, { 
        id: 2,
        name: '中班A3',
        begin: '',
        end: '',
        status: '1',
        wxworkGroupName: '',
        wxworkName: '中班A3',
        endBorder: false
      }, { 
        id: 3,
        name: '晚班A6',
        begin: '',
        end: '',
        status: '1',
        wxworkGroupName: '',
        wxworkName: '晚班A6',
        endBorder: false
      }]
      this.form.setFieldsValue({
        "wxworkGroupName": '', 
      })
      this.submitLoading = false
    },
 

    // 点击确认
    submit() {
      const { form: { validateFields } } = this
      validateFields((errors, values) => {
         
        if (errors) {
          console.log('表单检验未通过111',errors,values) 
          return
        } 
        const form_values = this.form.getFieldsValue() 
        console.log(form_values)

        // 判断是否选择时间
        let Num = []
        let setData = this.tableData.map((item, index) => { 
          if (!item.begin) {
            item.beginBorder = true
            Num.push(1)
          } else {
            item.beginBorder = false
          }
          if (item.end == '') {
            item.endBorder = true
            Num.push(1)
          } else {
            
            item.endBorder = false
             
          }
            
          return item
        })

        this.tableData = setData 
        if (Num.length > 0) {
          this.$message.error('请先选择排班时间')
          return false
        }    
            
        let newData = this.tableData.map(item => {
          return {
            id: item.id,
            name: item.name, 
            wxworkGroupName:form_values.wxworkGroupName,
            begin: moment(item.begin).format('HH:mm') + ':00',
            end: moment(item.end).format('HH:mm') + ':00',
            status: '1',
            wxworkName: item.wxworkName,
            isday: item.isday ? 1 : 0
          } 
        })
        newData.push({
          id: -1,
          name: '休息',
          begin: '',
          end: '',
          status: '1',
          wxworkGroupName: form_values.wxworkGroupName,
          wxworkName: '休息',
          isday: 0
        })
        let sendData = {
          wxworkGroupName: form_values.wxworkGroupName,
          shiftTypeList: newData
        }
        console.log(sendData)
        this.submitLoading = true
        if(this.editShow == 'edit'){
          UpdateTpShiftType(sendData).then(result => {
            this.submitLoading = false
            if(result.code == 200){
              this.$message.success(result.message) 
              this.removeData()
              this.visible = false
              // 存入缓存
              localStorage.setItem('timeDataAddLister', moment(new Date()).format('HH:mm:ss'))
              // this.$parent.$refs.table.loadData()
            }else{
              this.$message.error(result.message)
            }
          })
        }else{
          AddTpShiftType(sendData).then(result => {
            this.submitLoading = false
            if(result.code == 200){
              this.$message.success(result.message) 
              this.removeData()
              this.visible = false
              this.$parent.$refs.table.loadData()
            }else{
              this.$message.error(result.message)
            }
          })
        }
        

      })
    },

     
  },
}
</script>
<style lang="less" scoped>
/deep/ .no-user-input-style {
  input {
    border-color: red !important;
  }
}
.no-user-style {
  text-align: left;
  color: red;
  position: absolute;
  top: 29px;
  margin: 0 auto;
  left: 8%;
  background-color: #fff;
  width: 235px;
  z-index: 10;
  pointer-events: none;
}
/deep/ .text-area-style {
  width: 100%;
  .ant-form-item-control-wrapper {
    width: 75% !important;
  }
}
/deep/ .has-error .ant-form-explain,
.has-error .ant-form-split {
  color: #f5222d;
  position: absolute;
  top: 12px;
  left: 13px;
  background-color: #fff;
  width: 150px;
  pointer-events: none;
}

/deep/ .ant-calendar-time-picker-btn {
  display: none !important;
}
/deep/ .ant-form-inline .ant-form-item > .ant-form-item-label {
  width: 80px !important;
}
/deep/ .ant-form-inline .ant-form-item > .ant-form-item-control-wrapper {
  width: calc(100% - 80px) !important;
}
/deep/ .input-style {
  .ant-input-affix-wrapper .ant-input:not(:last-child) {
    padding-right: 46px !important;
  }
}

.events {
  list-style: none;
  margin: 0;
  padding: 0;
  padding-left: 15px;
  height: 100%;
}
.events .ant-badge-status {
  overflow: hidden;
  white-space: nowrap;
  // width: 100%;
  text-overflow: ellipsis;
  font-size: 12px;
}
.notes-month {
  text-align: center;
  font-size: 28px;
}
.notes-month section {
  font-size: 28px;
}
.popover-style {
  cursor: pointer;
}
/deep/.ant-fullcalendar-disabled-cell {
  .ant-fullcalendar-value {
    display: none !important;
  }
}
/deep/ .ant-radio-button-wrapper:last-child {
  display: none;
}
/deep/ .calendar-li-style {
  position: relative;
}
/deep/ .calendar-li-icon-style {
  font-size: 13px;
  position: absolute;
  right: 15px;
  top: 3px;
  cursor: pointer;
  width: 50px;
  display: block;
}
/deep/ .ant-form-inline .ant-form-item > .ant-form-item-label {
  width: 80px !important;
}
/deep/ .ant-form-inline .ant-form-item > .ant-form-item-control-wrapper {
  width: calc(100% - 80px) !important;
}
 .ant-calendar-time .ant-calendar-footer .ant-calendar-time-picker-btn{
   display: none !important;
 }
 /deep/ .colorBorder {
  input{
    border-color: red !important;
  }
  
}
</style>